#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>	
#include<stdlib.h>
#include<string.h>
#include<time.h>

void swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustDown(int* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			child++;
		}
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void CreateNDate()
{
	FILE* fin = fopen("data.txt", "w");
	int n = 10000;
	srand((unsigned)time(NULL));
	for (int i = 0; i < n; i++)
	{
		int x = rand() % 100000;
		fprintf(fin, "%d\n", x);
	}
	fclose(fin);
}

void PrintTopk(const char* file, int k)
{
	int* minHeap = (int*)malloc(sizeof(int) * k);
	if (minHeap == NULL)
	{
		perror("malloc failed!\n");
		exit(-1);
	}
	FILE* fin = fopen(file, "r");
	if (fin == NULL)
	{
		perror("fopen failed!\n");
		return;
	}
	for (int i = 0; i < k; i++)
	{
		fscanf(fin, "%d", &minHeap[i]);
	}
	for (int i = (k - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(minHeap, k, i);
	}
	int x = 0;
	while (fscanf(fin, "%d", &x)!=EOF)
	{
		if (x > minHeap[0])
		{
			minHeap[0] = x;
			AdjustDown(minHeap, k, 0);
		}
	}
	for (int i = 0; i < k; i++)
	{
		printf("%d ", minHeap[i]);
	}
}

int main()
{
	//CreateNDate();
	int k = 10;
	PrintTopk("data.txt", k);
	return 0;
}